package com.example.myapplication.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.R;
import com.example.myapplication.entity.Note;

import java.util.List;

public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.NoteViewHolder> {
    private List<Note> noteList;

    // ========== 创建 ViewHolder ==========
    @NonNull
    @Override
    public NoteAdapter.NoteViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.note_item, parent, false);
        return new NoteViewHolder(view);
    }
    
    // ========== 绑定数据 ==========
    @Override
    public void onBindViewHolder(@NonNull NoteAdapter.NoteViewHolder holder, int position) {
        if (noteList != null && position < noteList.size()) {
            Note note = noteList.get(position);
            holder.tvTitle.setText(note.getTitle());
            holder.tvContent.setText(note.getContent());
        }
    }
    
    // ========== 告诉 RecyclerView 一共有多少条数据 ==========
    @Override
    public int getItemCount() {
        return noteList != null ? noteList.size() : 0;
    }
    
    // 这个就是 setNotes() 方法！
    public void setNotes(List<Note> notes) {
        this.noteList = notes;
        notifyDataSetChanged(); // 通知 RecyclerView 数据更新
    }
    
    //内部类：ViewHolder,绑定视图的工具类，保存 item 里的控件引用
    public class NoteViewHolder extends RecyclerView.ViewHolder{
        TextView tvTitle;
        TextView tvContent;

        public NoteViewHolder(@NonNull View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.tvTitle);
            tvContent = itemView.findViewById(R.id.tvContent);
        }
    }
}


